package com.deram.ctin.serv.system.service.impl;

import com.deram.ctin.common.utils.BusinessUtils;
import com.deram.ctin.common.utils.DateUtils;
import com.deram.ctin.common.utils.PasswordUtils;
import com.deram.ctin.common.utils.ValidateUtils;
import com.deram.ctin.serv.system.entity.SysUser;
import com.deram.ctin.serv.system.entity.SystemUser;
import com.deram.ctin.serv.system.mapper.SystemUserMapper;
import com.deram.ctin.serv.system.service.SystemUserService;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Created by xhw on 2017/09/13.
 */

@Service
public class SystemUserServiceImpl implements SystemUserService {

    @Autowired
    private SystemUserMapper systemUserMapper;

    @Override
    public SystemUser find(Long id) {
        ValidateUtils.isId(id, "用户ID");
        SystemUser systemUser = systemUserMapper.selectById(id);
        return systemUser;
    }

    @Override
    public SystemUser findByUsername(String username) {
        ValidateUtils.notEmpty(username, "用户名");
        SystemUser systemUser = new SystemUser();
        systemUser.setUsername(username);
        SystemUser user = systemUserMapper.selectOne(systemUser);
        return user;
    }

    @Override
    public SystemUser create(SystemUser param) {
        SystemUser oldUser = this.findByUsername(param.getUsername());
        BusinessUtils.isNull(oldUser, "用户已存在");
        SystemUser obj = new SystemUser();
        obj.setUsername(param.getUsername());
        String salt = RandomStringUtils.randomAlphanumeric(10);
        obj.setSalt(salt);
        if (StringUtils.isNotEmpty(param.getPassword())) {
            String encryptStr = PasswordUtils.encrypt(param.getPassword(), obj.getSalt());
            obj.setPassword(encryptStr);
        }
        obj.setCreateDate(DateUtils.getNow());
        systemUserMapper.insert(obj);
        return obj;
    }

    @Override
    public void updatePassword(Long id, String newPassword) {
        ValidateUtils.isPassword(newPassword, "新密码");
        SystemUser user = find(id);
        String encryptStr = PasswordUtils.encrypt(newPassword, user.getSalt());
        user.setPassword(encryptStr);
        systemUserMapper.updateById(user);
    }

    @Override
    public void delete(Long id) {
        systemUserMapper.deleteById(id);
    }
}
